package com.xiyu.service.repository.customer.contact;

import com.xiyu.service.model.customer.contact.CustomerContact;
import com.xiyu.service.model.customer.contact.CustomerContactFetcher;
import com.xiyu.service.model.customer.contact.CustomerContactTable;
import com.xiyu.service.model.customer.info.CustomerInfoFetcher;
import org.babyfish.jimmer.spring.repository.JRepository;

import java.time.LocalDateTime;
import java.util.List;

public interface CustomerContactRepository extends JRepository<CustomerContact, Long> {
    CustomerContactTable customerContactTable = CustomerContactTable.$;

    default CustomerContact findMailContact(Long customerId){
        return sql().createQuery(customerContactTable)
                .where(customerContactTable.customerId().eq(customerId))
                .where(customerContactTable.isMain().eq(true))
                .select(customerContactTable)
                .fetchOptional().orElse(null);
    }

    default void updateDeleteTime(Long id){
        sql().createUpdate(customerContactTable)
                .where(customerContactTable.id().eq(id))
                .set(customerContactTable.deletedTime(), LocalDateTime.now())
                .execute();
    }

    default CustomerContact findDetailById(Long id){
        return sql().createQuery(customerContactTable)
                .where(customerContactTable.id().eq(id))
                .select(customerContactTable.fetch(CustomerContactFetcher.$.allTableFields()
                        .customer(CustomerInfoFetcher.$.allTableFields())
                ))
                .fetchOptional().orElse(null);
    }

    List<CustomerContact> findByCustomerId(Long customerId);


}